﻿namespace EFS.AD
{
	/// <summary>
	/// Current
	/// </summary>
	public static class Current
	{
		// get current AD user if any
		public static EFS.AD.User User
		{
			get
			{
				// user
				EFS.AD.User user = null;

				// use search
				using (System.DirectoryServices.DirectoryEntry rootDirectoryEntry = RootDirectoryEntry)
				{
					// use search
					using (System.DirectoryServices.DirectorySearcher adSearch = new System.DirectoryServices.DirectorySearcher(rootDirectoryEntry))
					{
						// search
						adSearch.Filter = System.String.Format("(sAMAccountName={0})", System.Environment.UserName);
						System.DirectoryServices.SearchResult adSearchResult = adSearch.FindOne();

						// check
						if (null != adSearchResult)
						{
							// use search
							using (System.DirectoryServices.DirectoryEntry directoryEntry = adSearchResult.GetDirectoryEntry())
							{
								// check
								if (null != adSearchResult)
								{
									user = Misc.Functions.UserFrom(directoryEntry);
								}
							}
						}
					}
				}

				//  check
				if (null == user)
				{
					// none
					throw new System.Exception(System.String.Format("Failed to get Directory Entry for {0}", System.Environment.UserName));
				}

				// done
				return user;
			}
		}

		/// <summary>
		/// Get loacal AD root entry; must be released
		/// </summary>
		/// <returns></returns>
		internal static System.DirectoryServices.DirectoryEntry RootDirectoryEntry
		{
			get
			{
				// check
				System.DirectoryServices.DirectoryEntry adDirectoryEntry = null;

				//get a directory entry for the Global catalog
				using (System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("GC:"))
				{
					//enumerate the root to get the root LDAP folder
					System.Collections.IEnumerator ie = entry.Children.GetEnumerator();

					//move the enumerator onto the first child
                    if (ie.MoveNext())
                    {
                        //get the directory entry for the LDAP root folder
                        adDirectoryEntry = (System.DirectoryServices.DirectoryEntry)ie.Current;

						// log
						EFS.EventLog.Log.LogInfo(System.String.Format("RootDirectoryEntry name = '{0}', path = '{1}'", adDirectoryEntry.Name, adDirectoryEntry.Path));
                    }
				}

				// check
				if (null == adDirectoryEntry)
				{
					// none
					throw new System.Exception("Failed to get Current Domain Root");
				}

				// done
				return adDirectoryEntry;
			}
		}
	}
}
